package net.xdclass.compoent;

import net.xdclass.strategy.ShardingDBConfig;
import net.xdclass.strategy.ShardingTableConfig;
import net.xdclass.utils.CommonUtil;
import org.springframework.stereotype.Component;

/**
 * @author ：zhouyang
 * @date ：Created in 2022/3/12 9:50
 * @modified By：
 * @version: $
 */
@Component
public class ShortLinkComponent {
    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    //生成短链码
    public  String createShortLinkCode(String param) {
        long murmurHash = CommonUtil.murmurHash32(param);
        String code = encodeToBase62(murmurHash);
        String shortLinkCode = ShardingDBConfig.getRandomDBPrefix(code) + code + ShardingTableConfig.getRandomTableSuffix(code);
        return shortLinkCode;
    }


    /**
     * 10进制转62进制
     *
     * @param num
     * @return
     */

    private static String encodeToBase62(long num) {

        //StringBuffer 线程安全  StringBuilder线程不安全
        StringBuffer buffer = new StringBuffer();
        do {
            int i = (int) (num % 62);
            buffer.append(CHARS.charAt(i));
            num = num / 62;

        } while (num > 0);
        String value = buffer.reverse().toString();
        return value;
    }

}
